package com.langxin.erp.biz;

import java.util.Date;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.langxin.erp.dao.UserDao;
import com.langxin.erp.model.UserInfo;
import com.langxin.erp.util.constant.SiteConstant;
import com.langxin.erp.util.security.Base64Code;
import com.langxin.erp.util.security.MD5Util;
import com.langxin.erp.util.web.ActionUtils;
import com.langxin.erp.util.web.CookieUtil;
import com.langxin.erp.util.web.JsonUtils;

/**
 * 用户业务
 * @author gu
 *
 */
@Service("userBiz")
public class UserBiz {

	@Resource
	private UserDao    userDao;
	
	
	/**
	 * 是否登陆成功
	 * @param adminInfo
	 * @return
	 */
	public boolean login(UserInfo userInfo){
		UserInfo user = userDao.query(userInfo.getName(), MD5Util.encode(userInfo.getPassword()));
		if(user == null){
			return false;
		}else{
			Date loginAt = user.getLoginAt();
			// 更新登录时间
			user.setLoginAt(new Date());
			userDao.update(user);
			user.setLoginAt(loginAt == null ? new Date() : loginAt);
			// 信息存放至session
			ActionUtils.getRequest().getSession().setAttribute(SiteConstant.SESSION_USER_KEY, user);
			// 保存至cookie
			CookieUtil.createCookie(ActionUtils.getResponse(), SiteConstant.CookieKey.USER_COOKIE.getValue(), Base64Code.encode(JsonUtils.toJson(user)), SiteConstant.COOKIE_DOMAIN, "/", -1);
			return true;
		}
	}
	
	/**
	 * 当前用用户退出
	 */
	public void logout(){
		ActionUtils.getRequest().getSession().setAttribute(SiteConstant.SESSION_USER_KEY,null);
		CookieUtil.createCookie(ActionUtils.getResponse(), SiteConstant.CookieKey.USER_COOKIE.getValue(), null, SiteConstant.COOKIE_DOMAIN, "/", -1);
		ActionUtils.getRequest().setAttribute(SiteConstant.SESSION_USER_KEY,null);
		ActionUtils.getRequest().getSession().invalidate();
		ActionUtils.getRequest().getSession(true);
	}
	
	/**
	 * 密码修改
	 * @param param
	 */
	public boolean updatePasswd(UserInfo userInfo){
		if(StringUtils.isBlank(userInfo.getPassword())){
			return false;
		}
		userInfo.setId(ActionUtils.getCurrentUser().getId());
		userInfo.setPassword(MD5Util.encode(userInfo.getPassword()));
		userDao.update(userInfo);
		return true;
	}
}
